package com.szh.es.testcase;


import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class AutoSuggestTest {

    private static final String INDEX_NAME = "hotel2";

    @Test
    public void testAutoSugg() throws IOException {
        // 创建客户端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200)));

        // 2-创建DSL
        SearchRequest request = new SearchRequest(INDEX_NAME);
        request.source().suggest(new SuggestBuilder().addSuggestion("suggestions",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix("h")
                        .skipDuplicates(true)
                        .size(10)
        ));

        // 发起请求
        SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

        //
        Suggest suggest = response.getSuggest();
        CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
        List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
        options.forEach(System.out::println);

        esClient.close();
    }
}
